<template>
	<view class="chat">
		<view class="chat-bg"></view>
		<scroll-view class="scroll" scroll-y show-scrollbar :scroll-into-view="toButtom" @scroll="showScroll">
			<view class="chat-info" :class="item.sendUser === 0 ? 'chat-self' : 'chat-chatter'"
				v-for="(item, index) in chatList" :key="index">
				<image :src="item.sendUser === 0 ? user.cover :  other.cover" mode="aspectFill"
					style="height: 120rpx; width: 120rpx; border-radius: 50%; margin-right: 15rpx; margin-bottom: auto;"
					@click="toInfo(item.sendUser,other.id)">
				</image>
				<view class="chat-message">
					<text class="text-main-xll">
						<div v-html="emojiReplace(item.sendMessage)"></div>
					</text>
				</view>
			</view>
			<view id="screenBottom" style="height: 12rpx;"></view>
		</scroll-view>
		<view class="padding-top-sm tabar_bottom" style="background-color: #00b4b3;">
			<view class="padding-bottom-sm flex padding-lr-sm" style="border-bottom: 1px solid #EEEEEE;">

				<button @click="uploadfile"
					style="position: relative;width: 12%;margin-right:1%;height: 60rpx;font-size: 24rpx;background-color: orange;">
					图片发送
				</button>
				<button @click="toVideo(other.id,other.username)"
					style="position: relative;width: 12%;margin-right:1%;height: 60rpx;font-size: 24rpx;background-color: orange;">
					视频通话
				</button>
				<view class="tools">
					<view class="clear" @click="clear">
						<uni-icons type="trash"
							style="font-size: 36px;margin-right: 20rpx;top: 20rpx;position: relative;width: 12%;"></uni-icons>
					</view>
				</view>
				<view class="flex-sub">
					<input type="text" @focus="InputFocus" @blur="InputBlur" v-model="other.sendMessage"
						@input="textareaBInput" placeholder-style="font-size:24px;color:#aaaaaa;"
						style="background-color: white; width: 96%;height: 60rpx;border-radius: 20px;padding: 5rpx;"
						placeholder="请输入您要发送的内容">
					<!-- <div v-html="emojiReplace(other.sendMessage)"></div> -->
					</input>
				</view>

				<view class="padding-right:4rpx;">
					<text :class="emojiIcon"
						style="font-size: 24px;margin-right: 20rpx;top: 20rpx;position: relative;width: 12%;"
						@click="showEmj"></text>
				</view>
				<button class="cu-btn bg-gradual-blue shadow-blur send"
					style="width: 20%;height: 60rpx; font-size: 24rpx;" @click="sendMessage">发送</button>

			</view>

			<view style="position: relative;">
				<emotion @emotion="handleEmj" :height="200" v-if="isShowEmj"></emotion>
			</view>
		</view>
	</view>
</template>

<script>
	import emotion from '../../components/bkhumor-emojiplus/bkhumor-emojiplus.vue'
	import {
		getDetail
	} from '@/common/mock/mock.js';
	import {
		getTime
	} from '@/utils/getTime.js';
	import {
		config
	} from '@/common/config.js';
	import listItem from '../../uni_modules/uview-ui/libs/config/props/listItem';
	export default {
		data() {
			return {
				isShowEmj: false,
				emojiIcon: 'cuIcon-emoji',
				chatList: [],
				user: {
					id: '',
					cover: ''
				},
				other: {
					id: '',
					username: '',
					cover: '',
					lastMessage: '',
					lastTime: '',
					sendMessage: ''
				},
				toButtom: '',
				socketMessage: '',
				send: 'animate__animated animate__flip',
				emoji: []
			}
		},
		components: {
			emotion
		},
		onLoad(option) {
			this.openSocket();
			if (option.id) {
				this.getData(option.id);
				this.other.id = option.id;
				this.other.username = option.username;
				console.log(option.id);
			};
			uni.setNavigationBarTitle({
				title: option.username
			});
			uni.setNavigationBarColor({
				frontColor: "#000000",
				backgroundColor: '#00b4b3'
			});
			this.other.cover = option.cover;
			this.user.cover = this.$store.state.chat_cover;
			// this.user.cover = this.$store.state.user.cover;
			this.InsertChatList(uni.getStorageSync(option.id))
			console.log(this.chatList);
			for (let i = 1; i <= 98; i++) {
				this.emoji.push('[em_' + i + ']');
			}
		},
		onUnload() {
			uni.setStorageSync(this.other.id, this.chatList);

			this.$store.state.noneMessage = false;
			console.log(this.$store.state.noneMessage)

			// uni.closeSocket({})
			console.log("关闭了当前对话...")
		},
		methods: {
			handleEmj(i, j) {
				if (i == '[em_98]') {
					//匹配最后一个表情符号并删除。
					this.other.sendMessage = this.other.sendMessage.replace(/(\[[^\]]+\]|[\s\S])$/, '');
				} else {
					this.other.sendMessage += i;
				}
			},
			emojiReplace(text) {
				for (let i = 0; i <= 98; i++) {
					if (this.other.sendMessage.search(this.emoji[i]) != -1) {
						this.other.sendMessage = this.other.sendMessage.replaceAll(this.emoji[i],
							`<img src="${config.url}emoji/download/${i}.gif" align="middle">`)
					}
				}
				return text;
			},
			textareaBInput(e) {
				this.other.sendMessage = e.detail.value
			},
			uploadfile() {
				uni.chooseImage({
					success: (res) => {
						console.log("res");
						console.log(res.tempFilePaths[0]);
						uni.uploadFile({
							url: config.url + 'file/upload',
							filePath: res.tempFilePaths[0],
							formData: {
								'username': ''
							},
							success: (res2) => {
								if (JSON.parse(res2.data).code == '-1') {
									uni.showModal({
										title: "图片发送失败！",
										content: "请稍后重试！"
									})
								} else {
									console.log("图片");
									console.log(JSON.parse(res2.data).data);
									let url = JSON.parse(res2.data).data
									uni.showLoading({
										title: '图片发送中'
									})
									this.other.sendMessage =
										`<img src="${url}" style="width:200px;height:150px;">`;
									this.sendMessage();
									setTimeout(() => {
										uni.hideLoading();
									}, 500);
									this.$u.toast("图片发送成功！");

								}
							}
						})
					}
				})
			},
			showEmj() {
				let bool = !this.isShowEmj;
				if (bool) {
					this.emojiIcon = 'cuIcon-keyboard';
				} else {
					this.emojiIcon = 'cuIcon-emoji';
				}
				this.isShowEmj = bool;
				this.$emit('show')
			},
			InputBlur(e) {

			},
			InputFocus(e) {
				this.isShowEmj = false;
				this.emojiIcon = 'cuIcon-emoji';
				this.$emit('foc')
			},
			getData(id) {
				// mock
				// getDetail(id).then((res) => {
				// 	this.boss.id = res._id.$oid,
				// 	this.boss.job = res.job,
				// 	this.boss.price = res.price,
				// 	this.boss.address = res.address,
				// 	this.boss.cover = res.cover,
				// 	this.boss.interviewer = res.interviewer,
				// 	// this.context = res.context,
				// 	this.boss.label = res.label,
				// 	this.boss.company = res.company,
				// 	this.chatData.bossImage = res.cover
				// })
			},
			showScroll() {
				console.log("滚了")
			},
			openSocket() {
				uni.connectSocket({
					// url: 'ws://localhost:3200'
					url: 'ws://localhost:3000/webSocket'
				});
				uni.onSocketError(function(res) {
					console.log('WebSocket连接打开失败，请检查！');
				});

				uni.onSocketOpen((res) => {
					console.log('WebSocket连接已打开！');
				});
			},
			sendMessage() {
				if (this.other.sendMessage) {
					// 我方接受数据
					// 还需设计

					let message = {
						to: this.$store.state.user._id,
						text: this.other.sendMessage
					};
					console.log(message)

					uni.sendSocketMessage({
						data: JSON.stringify(message)
						// data: JSON.stringify(this.chatData.sendMessage),
					}).then(() => {
						console.log("发送了" + JSON.stringify(message))
						// console.log("发送了" + this.chatData.sendMessage)
						let chat_self = {
							sendUser: 0,
							sendMessage: this.other.sendMessage
						}
						this.chatList.push(chat_self);
						// 存储最后一条数据
						this.other.lastMessage = this.other.sendMessage;
						// console.log("lastMessage")
						// console.log(this.other.lastMessage)
						this.other.lastTime = getTime();

						this.other.sendMessage = '';

						// 对方发送数据
						uni.onSocketMessage((res) => {
							console.log("res:");
							console.log(res);
							var obj = JSON.parse(res.data);
							if (obj.type == 'offer') {
								console.log("对方请求建立视频通讯");
								uni.showModal({
									title: this.other.username + "请求视频通话",
									content: '是否同意建立通话',
									duration: 3000,
									success: (res) => {
										if (res.confirm) {
											console.log('用户点击确认');
											uni.showLoading({
												title: '加载中'
											})
											this.toVideo(this.other.id, this.other.username)
											setTimeout(function() {
												uni.hideLoading();
												this.$u.toast("请点击连接");
											}, 1000);

										} else if (res.cancel) {
											uni.sendSocketMessage({
												data: JSON.stringify({
													type: 'cancel',
													msg: to + "拒绝了你的视频请求"
												})
											})
											console.log('用户点击取消')
											// #ifdef H5
											location.reload()
											// #endif
											// #ifndef H5
											this.$u.toast("暂时不支持该设备")
											// #endif
										}
									}

								});

							} 
								let data = JSON.parse(res.data)
								
									console.log("data.to :" + data.to);
									console.log("this.$store.state.user._id:" + this.$store.state.user._id)
									console.log("data.to != this.$store.state.user._id:" + data.to != this
										.$store.state.user._id)
									var chatter = data.text;
									console.log(chatter);
									let chat_chatter = {
										sendUser: 1,
										sendMessage: chatter
									}
									this.chatList.push(chat_chatter);

									this.other.lastMessage = chatter;
									this.other.lastTime = getTime();
									
								
							
						})
						console.log(this.other)
					}).catch(() => {
						uni.showToast({
							title: '通信开了会差┭┮﹏┭┮ 重新连接中',
							icon: 'none'
						});
						reconnect();
					})
				} else {
					uni.showToast({
						title: '请在输入框内填写内容...',
						icon: 'none'
					});
				}
				console.log(this.other)
				this.toBottom();
				// console.log(this.toButtom);
			},
			toBottom() {
				this.toButtom = 'screenBottom';
				// console.log(this.to)
			},
			toVideo(id, username) {
				this.$u.route('pages/video/video', {
					id: id,
					username: username
				});
			},
			InsertChatList(List) {
				for (let i = 0; i < List.length; i++) {
					this.chatList.push(List[i])
				}
			},
			clear() {
				this.chatList = []
				uni.showToast({
					title: '聊天记录已删除',
					icon: 'none'
				});
			},
			toInfo(id, user_id) {
				this.$u.route('pages/myInfo/myInfo', {
					id: id,
					user_id: user_id
				})
			}
		}
	}
</script>

<style lang="scss">
	.send {
		-webkit-animation: rotate-vert-center 1s;
		animation: rotate-vert-center 1s;
	}

	.send:active {
		animation: none;
	}

	page {
		// background: red;
	}

	.tabar_bottom {
		position: fixed;
		bottom: 0;
		z-index: 999;
		width: 100%;
		padding: 16rpx 0rpx;
		border-top: 1px solid #EEEEEE;
		box-sizing: border-box;
	}

	.chat-bg {
		height: 100vh;
		width: 100vw;
		background-image: linear-gradient(to top, #3f51b1 0%, #5a55ae 13%, #7b5fac 25%, #8f6aae 38%, #a86aa4 50%, #cc6b8e 62%, #f18271 75%, #f3a469 87%, #f7c978 100%);
		// background-image: linear-gradient(to top, gainsboro 0%, #ace0f9 100%);
		background-size: cover;
		box-sizing: border-box;
		position: fixed;
		z-index: 0;
	}


	.chat {
		background: gainsboro;
		width: 100%;

		.scroll {
			height: 82vh;

			.chat-info {
				display: flex;
				align-items: center;
				margin-bottom: 12rpx;

				.chat-message {

					max-width: 80%;
					padding: 15rpx;
					font-weight: bold;
					border-radius: 15rpx;
					box-shadow: rgba(60, 64, 67, 0.3) 0rpx 1rpx 2rpx 0rpx, rgba(60, 64, 67, 0.15) 0rpx 1rpx 3rpx 1rpx;
				}
			}

			.chat-chatter {
				margin-left: 15rpx;

				.chat-message {
					background-image: linear-gradient(-225deg, #fffeff 0%, #d7fffe 100%);
				}
			}

			.chat-self {
				flex-direction: row-reverse;
				margin-left: auto;

				.chat-message {
					margin: 10rpx;
					background-image: linear-gradient(-20deg, #e9defa 0%, #fbfcdb 100%);
				}

			}


		}

		.zhanweifu {
			height: 175rpx;
		}



		.input-box {
			position: fixed;
			z-index: 99;
			bottom: 0;
			width: 100%;
			height: 8vh;
			padding: 10px;
			display: flex;
			flex-direction: row;
			align-items: center;
			background: white;

			.tools {
				background: red;
				height: 6vh;
				z-index: 99;
				width: 10vw;
				border-radius: 20rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				-webkit-animation: tan 1s;
				animation: tan 1s;
			}

			.tools:active {
				animation: none;
			}

			input {
				float: left;
				width: 58vw;
				border: 1px solid black;
				border-radius: 20px;
				height: 50%;
				margin-left: 2%;
				padding: 5px 5px 5px 15px;
				background: white;
			}

			button {
				position: absolute;
				float: left;
				left: 76%;
				width: 20vw;
				height: 50%;
				margin-right: 10rpx;
				border-radius: 20rpx;
				background: $boss-base-color;
				text-align: center;
				// align-items: center;
			}
		}
	}
</style>